﻿@inject DemoThemeService Themes
@implements IDisposable
@implements IDemoThemeLoadNotifier

<div class="themeswitcher-container shadow @StateCssClass">
    @if(IsLoaded) {
        <DxScrollView CssClass="blazor-themes">
            <div class="list-group list-group-flush">
                @foreach(var themeSet in Themes.ThemeSets) {
                    <span class="themeswitcher-group card-header list-group-item">@themeSet.Title</span>
                    @foreach(var theme in themeSet.Themes) {
                        <ThemeSwitcherItem Theme="@theme" Click="ThemeSwitcherItem_Click"/>
                    }
                }
            </div>
        </DxScrollView>
    }
</div>

@code {
    [Parameter]
    public bool Shown { get; set; }
    [Parameter]
    public EventCallback<bool> ShownChanged { get; set; }
    [Parameter]
    public string ThemeName { get; set; }
    [Parameter]
    public EventCallback<string> ThemeNameChanged { get; set; }

    string StateCssClass { get { return IsLoaded ? ((Shown? "themeswitcher-container-shown" : "themeswitcher-container-hidden")) : ""; } }
    bool IsLoaded { get; set; }

    protected override void OnInitialized() {
        base.OnInitialized();
        Themes.ThemeLoadNotifier = this;
    }

    async Task ThemeSwitcherItem_Click(DemoTheme theme) {
        Themes.ThemeChangeRequestDispatcher?.RequestThemeChange(theme);
        await ToggleThemeSwitcherPanel(false);
    }

    public async Task NotifyThemeLoadedAsync(DemoTheme theme) {
        ThemeName = theme.Name;
        await ThemeNameChanged.InvokeAsync(ThemeName);
    }

    async Task ToggleThemeSwitcherPanel(bool shown) {
        if(shown != Shown) {
            Shown = shown;
            await ShownChanged.InvokeAsync(shown);
        }
    }

    protected override void OnAfterRender(bool firstRender) {
        if(firstRender) {
            IsLoaded = true;
            if(Shown)
                StateHasChanged();
        }
    }

    public void Dispose() {
        Themes.ThemeLoadNotifier = null;
    }
}
